package stack;

import java.util.Stack;

//                                     括号匹配问题
public class Practice2 {
    public boolean isValid(String s) {
        //使用栈来解决
        //1.先创建一个栈
        Stack<Character> stack = new Stack<>();
        //2.遍历字符串 '('或 '['或 '{'入栈
        //  反之与栈顶元素进行匹配,并出栈
        for (int i = 0; i < s.length(); i++){
            char elem = s.charAt(i);
            if (elem == '(' || elem == '[' || elem == '{'){
                stack.push(elem);
                continue;
            }
            if (elem == ')' || elem ==']' || elem == '}'){
                //判断栈是否为空
                if (stack.isEmpty()){
                    return false;
                }
                char pop = stack.pop();
                if (pop == '(' && elem == ')'){
                    continue;
                }
                if (pop == '[' && elem == ']'){
                    continue;
                }
                if (pop == '{' && elem == '}'){
                    continue;
                }
            }
            return false;
        }
        //3.判断栈是否为空
        if (stack.isEmpty()){
            return true;
        }
        return false;
    }
}
